package health.lm.com.component_base.base.mvp.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.launcher.ARouter;
import com.gyf.immersionbar.ImmersionBar;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.vondear.rxtool.RxActivityTool;

import butterknife.Unbinder;
import health.lm.com.component_base.R;
import health.lm.com.component_base.base.event.BusProvider;
import health.lm.com.component_base.base.mvp.kit.KnifeKit;
import health.lm.com.component_base.base.mvp.contract.VDelegateBase;
import health.lm.com.component_base.base.mvp.inner.IPresent;
import health.lm.com.component_base.base.mvp.inner.IView;
import health.lm.com.component_base.base.mvp.inner.VDelegate;


/**
 * Created by wanglei on 2016/12/29.
 */
public abstract class XActivity<P extends IPresent> extends RxAppCompatActivity implements IView<P> {
    public XActivity mActivity;
    private VDelegate vDelegate;
    private P p;
    protected Activity context;
    protected RxPermissions rxPermissions;
    private Unbinder unbinder;
    public ImmersionBar mImmersionBar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RxActivityTool.addActivity(this);
        context = this;
        mActivity = this;
        getP();
        //沉浸式状态栏
        initImmersionBar();
        setImmersionBar();
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        rxPermissions = new RxPermissions(this);
        ARouter.getInstance().inject(this);
        if (getLayoutId() > 0) {
            setContentView(getLayoutId());
            bindUI(null);
            bindEvent();
        }
        initData(savedInstanceState);

    }

    @Override
    public void bindUI(View rootView) {
        unbinder = KnifeKit.bind(this);
    }

    protected VDelegate getvDelegate() {
        if (vDelegate == null) {
            vDelegate = VDelegateBase.create(context);
        }
        return vDelegate;
    }

    protected P getP() {
        if (p == null) {
            p = newP();
        }
        if (p != null) {
            if (!p.hasV()) {
                p.attachV(this);
            }
        }
        return p;
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (useEventBus()) {
            BusProvider.getBus().register(this);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        getvDelegate().resume();
    }


    @Override
    protected void onPause() {
        super.onPause();
        getvDelegate().pause();
    }

    @Override
    public boolean useEventBus() {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (useEventBus()) {
            BusProvider.getBus().unregister(this);
        }
        if (getP() != null) {
            getP().detachV();
        }
        KnifeKit.unbind(unbinder);
        getvDelegate().destory();
        p = null;
        vDelegate = null;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (getOptionsMenuId() > 0) {
            getMenuInflater().inflate(getOptionsMenuId(), menu);
        }
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public int getOptionsMenuId() {
        return 0;
    }

    @Override
    public void bindEvent() {

    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.bindToLifecycle();
    }

    private void initImmersionBar() {
        mImmersionBar = ImmersionBar.with(this);
        //所有子类都将继承这些相同的属性
//         mImmersionBar.init();
    }

    protected void setImmersionBar() {
        mImmersionBar.statusBarColor(R.color.colorPrimary).statusBarDarkFont(true).init();
    }

    /**
     * 打开一个Activity 默认 不关闭当前activity
     */
    public void gotoActivity(Class<?> clz) {
        gotoActivity(clz, false, null);
    }

    public void gotoActivity(Class<?> clz, boolean isCloseCurrentActivity) {
        gotoActivity(clz, isCloseCurrentActivity, null);
    }

    public void gotoActivity(Class<?> clz, boolean isCloseCurrentActivity, Bundle ex) {
        Intent intent = new Intent(this, clz);
        if (ex != null) intent.putExtras(ex);
        startActivity(intent);
        if (isCloseCurrentActivity) {
            mActivity.finish();
        }
    }

    /**
     * 无参数传递跳转到Activity
     * 无跳转动画
     * 基于Arouter
     */
    public void gotoActivity(String path) {
        gotoActivity(path, false);
    }

    public void gotoActivity(String path, boolean isCloseCurrentActivity) {
        ARouter.getInstance().build(path).navigation();
        if (isCloseCurrentActivity) {
            mActivity.finish();
        }
    }

    /**
     * 带参数传递跳转到Activity
     * 无跳转动画
     * 基于Arouter
     */
    public Postcard withValueActivity(String path) {
        return withValueActivity(path, false);
    }

    public Postcard withValueActivity(String path, boolean isCloseCurrentActivity) {
        Postcard aRouter = ARouter.getInstance().build(path);
        if (isCloseCurrentActivity) {
            mActivity.finish();
        }
        return aRouter;
    }

    //==========================点击屏幕自动隐藏键盘================================//
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                InputMethodManager imm =
                        (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS
                );
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    // Return whether touch the view.
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }
    //==========================点击屏幕自动隐藏键盘================================//

    protected View empty() {
        View view = LayoutInflater.from(context).inflate(R.layout.view_empty, null);
        return view;
    }
}
